import { type FC, useRef } from 'react';
import { useMemoizedFn } from 'ahooks';
import { createLoadMore } from '@/components';
import type { Post } from '@/typings/post';
import PostItem from '@/components/PostItem';
import type { InstanceType } from '@/components/LoadMore/types';
import { datas } from './mock';
import styles from './styles';

type PageContentProps = {
  pageKey: string;
  setIndex: (index: number) => void;
}

const createDatas = () => {
  const now = Date.now();
  return datas.map((item, i) => {
    const id = `${now}_${i}`;
    return { ...item, id: id };
  });
}

const wait = () => new Promise(r => {
  setTimeout(r, 3000);
});

const LoadMore = createLoadMore<Post.PostDetails>();

const PageContent: FC<PageContentProps> = (props) => {
  const { pageKey, setIndex } = props;
  const isRecommend = pageKey === 'recommend';
  const instanceRef = useRef<InstanceType>(null);
  const btnText = isRecommend ? 'Refresh' : 'Discover';

  const onBtnClick = useMemoizedFn(async () => {
    const instance = instanceRef.current!;
    if (!isRecommend) {
      setIndex(0);
    } else {
      instance.refresh();
    }
  });

  const emptyProps = {
    btnText,
    onBtnClick
  }

  return (
    <LoadMore
      ref={instanceRef}
      emptyProps={emptyProps}
      divideLineStyle={styles.space}
      request={async (params) => {
        await wait();
        return {
          total: 9,
          list: createDatas()
        }
      }}
      renderItem={({ item }) => {
        return (
          <PostItem
            postDetails={item}
          />
        );
      }}
    />
  );
}

export default PageContent;